package com.uetoken.cn.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.EncodeUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.qmuiteam.qmui.util.QMUIKeyboardHelper;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.sulink.numberkeyboard.popWindow.BasePayPop;
import com.sulink.numberkeyboard.popWindow.SimplePayPopWindow;
import com.uetoken.cn.R;
import com.uetoken.cn.adapter.AddTransferUserAdapter;
import com.uetoken.cn.adapter.holder.FundInfoHolder;
import com.uetoken.cn.adapter.holder.MultiUserTransferHolder;
import com.uetoken.cn.adapter.holder.UserTransferHolder;
import com.uetoken.cn.adapter.model.AddTransferUserModel;
import com.uetoken.cn.base.BaseActivity;
import com.uetoken.cn.bean.CheckUserInfoBean;
import com.uetoken.cn.bean.ConfigBean;
import com.uetoken.cn.bean.ExchangeRateBean;
import com.uetoken.cn.bean.MinTransferNumBean;
import com.uetoken.cn.bean.MsgBean;
import com.uetoken.cn.bean.PurseListBean;
import com.uetoken.cn.bean.SubPursesBean;
import com.uetoken.cn.common.ApiHelper;
import com.uetoken.cn.common.Constant;
import com.uetoken.cn.network.OkHttpUtils;
import com.uetoken.cn.network.Params;
import com.uetoken.cn.network.WebResponse;
import com.uetoken.cn.utils.ArithUtils;
import com.uetoken.cn.utils.KeybordUtils;
import com.uetoken.cn.utils.Save2DecimalUtils;
import com.uetoken.cn.view.DialogHelper;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class TransferAccountsActivity extends BaseActivity implements WebResponse, Handler.Callback,
        UserTransferHolder.OnSingleTransferClickListener, AddTransferUserAdapter.OnIsBatchTransferClickListener, AddTransferUserAdapter.OnItemClickListener {
    @BindView(R.id.topbar)
    QMUITopBar mTopbar;
    @BindView(R.id.rootFundInfoLayout)
    FrameLayout rootFundInfoLayout;
    @BindView(R.id.rootTransferLayout)
    FrameLayout rootTransferLayout;
    @BindView(R.id.detailTv)
    TextView mDetailTv;
    @BindView(R.id.massTransferBtn)
    Button mMassTransferBtn;
    @BindView(R.id.transferBtn)
    Button mTransferBtn;
    @BindView(R.id.detailsLayout)
    LinearLayout detailsLayout;

    @BindView(R.id.exchangeLayout)
    LinearLayout exchangeLayout;
    @BindView(R.id.serviceChargeTv)
    TextView serviceChargeTv;
    @BindView(R.id.serviceChargeComputeTv)
    TextView serviceChargeComputeTv;

    private View mView1;
    private View mView2;
    private View mView3;

    private AddTransferUserAdapter mAddTransferUserAdapter;
    private boolean isBatch = false;//判断是否是批量转账 true:批量转账； false：单个转账

    /**
     * 钱包转账网络请求码
     */
    private static final int NETWORK_REQUEST_SUB_PURSES = 10;
    /**
     * 钱包转账网络请求码
     */
    private static final int NETWORK_REQUEST_PURSE_TRANSFER = 11;
    /**
     * 钱包转账网络请求码
     */
    private static final int NETWORK_REQUEST_USER_INFO = 12;
    /**
     * 钱包转账网络请求码
     */
    private static final int INTENT_REQUEST_TRANSFER_CODE = 13;
    /**
     * 钱包转账网络请求码
     */
    private static final int NETWORK_REQUEST_EXCHANGERATEBY_PURSES = 14;
    /**
     * 钱包转账网络请求码
     */
    private static final int NETWORK_REQUEST_MINTRANSFER_NUM = 15;
    /**
     * 子钱包id
     */
    private String purseid;
    /**
     * 钱包单位名
     */
    private String purseunitname;
    /**
     * 钱包名
     */
    private String purseName;
    /**
     * 子钱包余额
     */
    private String balance;
    /**
     * 子钱包冻结
     */
    private String freeze;

    /**
     * 当前选择的钱包的图标
     */
    private String pursepic;
    /**
     * 转入方账号
     */
    private String mUserAccount;//转入方账号
    /**
     * 转账金额
     */
    private String mTransferAmount;//转账金额
    /**
     * 批量转账用户总数量
     */
    private String mBatchUserAccount = "0";//批量转账用户总数量
    /**
     * 批量转账总金额
     */
    private String mBatchTransferTotalAmount = "0.0";//批量转账总金额
    /**
     * 需转账用户总数量
     */
    private String mNeedBatchUserAccount = "0";//需转账用户总数量
    /**
     * 钱包类型ID
     * 钱包分类
     */
    private int pursetypeid;
    /**
     * 钱包ID
     */
    private int mId;
    /**
     * 钱包类型
     */
    private int pursetype;
    /**
     * 钱包余额，显示用
     */
    private String mBalanceformat;
    private String pagetransfer;//单个转账--提示说明
    private String pagetransfers;//多个转账--提示说明

    private FundInfoHolder mFundInfoHolder;
    private Handler mHandler;
    private Thread mThread;
    private MultiUserTransferHolder mMultiUserTransferHolder;
    private UserTransferHolder mUserTransferHolder;
    private List<AddTransferUserModel> mAddTransferUserModelList;
    public static TransferAccountsActivity mTransferAccountsActivity;
    private AddTransferUserModel model;
    private AddTransferUserModel mModificationAddTransferModel;
    private QMUIDialog mQMUIDialog;
    private boolean isCheck = false;
    private int batchTransferNumber;
    private int pointer;
    /**
     * 需转账总金额
     */
    private String transferAmountTotal;
    private boolean isComplete = true;
    private boolean isBatchModification = false;
    private boolean isChildPurse;
    private PurseListBean.DataBean mDataBean;
    private String exchangeRate;//汇率
    private static final int scale = 2;
    private String transferFeeTip;
    private String[] transferFeeTips;
    private String serviceChargeRate;
    private String mDOSRate;//换算DOS比
    private int decimalPlaces = 2;//输入金额小数点位数
    private String mAmountMovement;//金额动向
    private String mMinTransferNum = "1";
    private String percent;
    private SimplePayPopWindow simplePayPopWindow;

    @Override
    public int getLayoutId() {
        return R.layout.activity_transfer_accounts;
    }

    @Override
    public void initView() {
        // 沉浸式状态栏
        QMUIStatusBarHelper.translucent(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            QMUIStatusBarHelper.setStatusBarLightMode(this);
        }
        ButterKnife.bind(this);
        mHandler = new Handler(this);
        mTransferAccountsActivity = this;
        initTopBar();
        if (mFundInfoHolder == null) {
            mView1 = LayoutInflater.from(this).inflate(R.layout.item_fund_info, null);
            mFundInfoHolder = new FundInfoHolder(mView1);
            mView1.setTag(mFundInfoHolder);
        } else {
            mFundInfoHolder = (FundInfoHolder) mView1.getTag();
        }

        rootFundInfoLayout.addView(mView1);
        initTransferUserView();
    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        mDataBean = (PurseListBean.DataBean) intent.getSerializableExtra("assetsDetailModel");
        freeze = intent.getStringExtra("freeze");
        pagetransfer = intent.getStringExtra("pagetransfer");
        pagetransfers = intent.getStringExtra("pagetransfers");
        isChildPurse = intent.getBooleanExtra("isChildPurse", false);
        transferFeeTip = intent.getStringExtra("transferFeeTip");
        balance = mDataBean.getBalance();
        purseid = mDataBean.getPurseid() + "";
        purseunitname = mDataBean.getPurseunitname();
        purseName = mDataBean.getPursename();
        pursepic = mDataBean.getPursepic();
        pursetypeid = mDataBean.getPursetypeid();
        mId = mDataBean.getId();
        pursetype = mDataBean.getPursetype();
        //    小数点后精度：
//    BTC 小数点后8位
//    ETH 小数点后5位
//    USDT 小数点后8位
//    EOS 小数点后4位
//    BCH 小数点后8位
        if (pursetype == Constant.BTC_PURSE || pursetype == Constant.USDT_PURSE || pursetype == Constant.BCH_PURSE) {
            decimalPlaces = 8;
            mAmountMovement = getResources().getString(R.string.str_in_trading);
        } else if (pursetype == Constant.ETH_PURSE) {
            decimalPlaces = 5;
            mAmountMovement = getResources().getString(R.string.str_in_trading);
        } else if (pursetype == Constant.EOS_PURSE) {
            decimalPlaces = 4;
            mAmountMovement = getResources().getString(R.string.str_in_trading);
        } else {
            mAmountMovement = getResources().getString(R.string.str_in_trading);
            decimalPlaces = 2;
        }
        BigDecimal bigDecimal1 = new BigDecimal(balance);
        bigDecimal1.setScale(decimalPlaces, BigDecimal.ROUND_HALF_DOWN);
        mBalanceformat = bigDecimal1.toPlainString();
        mBalanceformat = ArithUtils.zeroFormat(mBalanceformat, decimalPlaces);

        BigDecimal bigDecimal2 = new BigDecimal(freeze);
        bigDecimal2.setScale(decimalPlaces, BigDecimal.ROUND_HALF_DOWN);
        freeze = bigDecimal2.toPlainString();
        freeze = ArithUtils.zeroFormat(freeze, decimalPlaces);

        if (!ObjectUtils.isEmpty(transferFeeTip)) {
            transferFeeTips = transferFeeTip.split(",");
            serviceChargeRate = transferFeeTips[0];
            mDOSRate = transferFeeTips[1];
            percent = ArithUtils.percent(serviceChargeRate, scale);
        }

        if (pursetypeid == 3) {
            getExchangeRateByPurse();
            getMinTransferNum();
        }
        Message message = new Message();
        message.what = Constant.HANDLER_MESSAGE_WHAT_1102;
        mHandler.sendMessage(message);
    }

    @Override
    public void init() {

    }

    private void initTopBar() {
        mTopbar.setTitle(R.string.transfer_accounts_txt);
        mTopbar.addLeftImageButton(R.drawable.ic_back, R.id.qmui_topbar_item_left_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isBatch) {
                    initTransferUserView();
                } else {
                    finish();
                }
            }
        });
    }

    private void initTransferUserView() {
        isComplete = true;
        mBatchUserAccount = "0";
        mBatchTransferTotalAmount = "0.0";
        mNeedBatchUserAccount = "0";
        transferAmountTotal = "0";
        if (mAddTransferUserAdapter != null) {
            mAddTransferUserAdapter.removeAllData();
        }
        Message message = new Message();
        message.what = Constant.HANDLER_MESSAGE_WHAT_1100;
        mHandler.sendMessage(message);
    }

    @Override
    public void onSuccessResponse(Call call, String response, int requestCode) throws IOException {
        LogUtils.dTag("onSuccessResponse== TRANSFER", "response = " + response + " requestCode = " + requestCode);
        switch (requestCode) {
            case NETWORK_REQUEST_SUB_PURSES:
                dissmissDialog();
                SubPursesBean mSubPursesBean = new Gson().fromJson(response, SubPursesBean.class);
                SubPursesBean.DataBean mSubPursesDataBean = mSubPursesBean.getData().get(0);
//                typeid = mSubPursesDataBean.getTypeid() + "";
                if (mSubPursesBean.getResult() > 0) {
                    if (mFundInfoHolder != null) {
                        mFundInfoHolder.mWalletNameTv.setText(purseName);
                        mFundInfoHolder.mAmountTv.setText(mBalanceformat);
                        mFundInfoHolder.mFreezeLimitTv.setText(mAmountMovement + " " + freeze);
                    }
                } else {
                    ToastUtils.showShort(mSubPursesBean.getMessage());
                }
                break;
            case NETWORK_REQUEST_USER_INFO:
                dissmissDialog();
                CheckUserInfoBean mCheckUserInfoBean = new Gson().fromJson(response, CheckUserInfoBean.class);
                if (mCheckUserInfoBean.getResult() > 0) {
                    isCheck = true;
                    if (mUserTransferHolder != null) {
                        mUserTransferHolder.mAccountInfoLayout.setVisibility(View.VISIBLE);
                        CheckUserInfoBean.DataBean mCheckUserInfoDataBean = mCheckUserInfoBean.getData();
                        mUserTransferHolder.mUserNameTv.setText(mCheckUserInfoDataBean.getNodename());
                        mUserTransferHolder.mUserPhoneNumberTv.setText(mCheckUserInfoDataBean.getMobileno());
                    }
                } else {
                    isCheck = false;
                    if (mUserTransferHolder != null) {
                        mUserTransferHolder.mAccountInfoLayout.setVisibility(View.GONE);
                    }
                    ToastUtils.showShort(mCheckUserInfoBean.getMessage());
                }
                break;
            case NETWORK_REQUEST_PURSE_TRANSFER:
                MsgBean mMsgBean = new Gson().fromJson(response, MsgBean.class);
                if (isBatch) {
                    if (mMsgBean.getResult() > 0) {
                        model.setStatus(Constant.BATCH_TRANSFER_SUCCEED);
                    } else {
                        model.setStatus(Constant.BATCH_TRANSFER_FAIL);
                    }

                    mAddTransferUserAdapter.updateIitem(model.getId());
                    if (pointer == (batchTransferNumber - 1)) {
                        simplePayPopWindow.dismiss();
                        Message message = new Message();
                        message.what = Constant.HANDLER_MESSAGE_WHAT_1103;
                        mHandler.sendMessage(message);
                    }
                    mThread.interrupt();
                } else {
                    if (mMsgBean.getResult() > 0) {
                        finish();
                    } else {
                        dissmissDialog();
                    }
                }

                ToastUtils.showShort(mMsgBean.getMessage());
                break;
            case NETWORK_REQUEST_EXCHANGERATEBY_PURSES:
                dissmissDialog();
                ExchangeRateBean mExchangeRateBean = new Gson().fromJson(response, ExchangeRateBean.class);
                if (mExchangeRateBean.getResult() > 0) {
                    ExchangeRateBean.DataBean mDataBean = mExchangeRateBean.getData();
                    exchangeRate = mDataBean.getPrice();
                    if (isBatch) {
                        mMultiUserTransferHolder.currentExchangeRateEt.setText(exchangeRate);
                        String serviceCharge = ArithUtils.serviceCharge(mBatchTransferTotalAmount, exchangeRate, serviceChargeRate, scale);
                        String serviceChargeDOS = ArithUtils.serviceChargeDOS(mBatchTransferTotalAmount, exchangeRate, serviceChargeRate, mDOSRate, scale);
                        serviceChargeTv.setText(serviceChargeDOS);
                        serviceChargeComputeTv.setText(String.format(getString(R.string.str_compute_service_charge),
                                mBatchTransferTotalAmount, exchangeRate, percent, serviceCharge + purseunitname, serviceChargeDOS));
                    } else {
                        mUserTransferHolder.currentExchangeRateEt.setText("￥" + exchangeRate);
                    }
                } else {
                    ToastUtils.showShort(mExchangeRateBean.getMessage());
                }
                break;
            case NETWORK_REQUEST_MINTRANSFER_NUM:
                dissmissDialog();
                MinTransferNumBean mMinTransferNumBean = new Gson().fromJson(response, MinTransferNumBean.class);
                if (mMinTransferNumBean.getResult() > 0) {
                    mMinTransferNum = mMinTransferNumBean.getData();
                } else {
                    ToastUtils.showShort(mMinTransferNumBean.getMessage());
                }
                break;
        }
    }

    @Override
    public void onFailResponse(Call call, IOException e, int requestCode) {
//        LogUtils.dTag("onSuccessResponse== TRANSFER", "onSuccessResponse== TRANSFER onFailResponse = " + e.toString());
        ToastUtils.showShort(R.string.network_anomaly_please_again);
        switch (requestCode) {
            case NETWORK_REQUEST_SUB_PURSES:
                dissmissDialog();
                break;
            case NETWORK_REQUEST_USER_INFO:
                dissmissDialog();
                isCheck = false;
                break;
            case NETWORK_REQUEST_PURSE_TRANSFER:
                if (isBatch) {
                    isComplete = false;
                    model.setStatus(Constant.BATCH_TRANSFER_FAIL);
                    mAddTransferUserAdapter.updateIitem(model.getId());
                    if (pointer == (batchTransferNumber - 1)) {
                        simplePayPopWindow.dismiss();
                        Message message = new Message();
                        message.what = Constant.HANDLER_MESSAGE_WHAT_1103;
                        mHandler.sendMessage(message);
                    } else {
                        mThread.interrupt();
                    }
                } else {
                    dissmissDialog();
                }
                break;
            default:
                dissmissDialog();
                break;
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case Constant.HANDLER_MESSAGE_WHAT_1100:
                isComplete = true;
                mBatchUserAccount = "0";
                mBatchTransferTotalAmount = "0.00";
                isBatch = false;
                mMassTransferBtn.setVisibility(View.VISIBLE);
                if (mView3 != null) {
                    rootTransferLayout.removeView(mView3);
                }
                if (mUserTransferHolder == null) {
                    mView2 = LayoutInflater.from(this).inflate(R.layout.item_solo_transfer_context, null);
                    mUserTransferHolder = new UserTransferHolder(mView2);
                    mView2.setTag(mUserTransferHolder);
                } else {
                    mUserTransferHolder = (UserTransferHolder) mView2.getTag();
                }
                mUserTransferHolder.setOnSingleTransferClickListener(this);
                rootTransferLayout.addView(mView2);

                initTextChangedListener();
                exchangeLayout.setVisibility(View.GONE);
                mUserTransferHolder.mAvailableBalanceValTv.setText(Save2DecimalUtils.getDecimalPrecision(balance, 2));
                detailsLayout.setBackgroundColor(ContextCompat.getColor(TransferAccountsActivity.this, R.color.durban_White));
                mDetailTv.setText(pagetransfer.replace("\\n", "\n"));
                if (pursetypeid == 3) {
                    mUserTransferHolder.currentExchangeRateLayout.setVisibility(View.VISIBLE);
                    mUserTransferHolder.amountEnteredLayout.setOrientation(LinearLayout.VERTICAL);
                    mUserTransferHolder.mDelIv.setVisibility(View.GONE);
                    mUserTransferHolder.unitLayout.setVisibility(View.VISIBLE);
                    mUserTransferHolder.mAvailableBalanceLayout.setVisibility(View.GONE);
                    mUserTransferHolder.currentExchangeRateEt.setText("");
                    mUserTransferHolder.monetaryUnitTv.setText(purseunitname);
                }
                break;
            case Constant.HANDLER_MESSAGE_WHAT_1101:
                isBatch = true;
                mUserAccount = "";
                mTransferAmount = "";
                if (mUserTransferHolder != null) {
                    isCheck = false;
                    mUserTransferHolder.mAccountEt.setText("");
                    mUserTransferHolder.mAmountEnteredEt.setText("");
                    mUserTransferHolder.mAccountInfoLayout.setVisibility(View.GONE);
                }
                mMassTransferBtn.setVisibility(View.GONE);
                if (mView2 != null) {
                    rootTransferLayout.removeView(mView2);
                }
                if (mMultiUserTransferHolder == null) {
                    mAddTransferUserModelList = new ArrayList<>();
                    mView3 = LayoutInflater.from(this).inflate(R.layout.item_multi_user_transfer_context, null);
                    mMultiUserTransferHolder = new MultiUserTransferHolder(mView3);
                    mView3.setTag(mMultiUserTransferHolder);
                } else {
                    mMultiUserTransferHolder = (MultiUserTransferHolder) mView3.getTag();
                }
                if (mQMUIDialog == null) {
                    mQMUIDialog = initAddTransferDialog();
                }
                rootTransferLayout.addView(mView3);
                detailsLayout.setBackgroundColor(ContextCompat.getColor(TransferAccountsActivity.this, R.color.app_color_xml_bg));
                mDetailTv.setText(pagetransfers.replace("\\n", "\n"));
//                mDetailTv.setText(R.string.transfer_details_txt_2);
                mMultiUserTransferHolder.mUserNumberTv.setText(Html.fromHtml(getResources().getString(R.string.total_user_txt, mBatchUserAccount)));
                mMultiUserTransferHolder.mTotalMoneyTv.setText(Html.fromHtml(getResources().getString(R.string.total_money_txt, "0.00")));
                if (pursetypeid == 3) {

                    mMultiUserTransferHolder.currentExchangeRateEt.setText(exchangeRate);
                    String serviceCharge = ArithUtils.serviceCharge(mBatchTransferTotalAmount, exchangeRate, serviceChargeRate, scale);
                    String serviceChargeDOS = ArithUtils.serviceChargeDOS(mBatchTransferTotalAmount, exchangeRate, serviceChargeRate, mDOSRate, scale);
                    serviceChargeTv.setText(serviceChargeDOS);
                    serviceChargeComputeTv.setText(String.format(getString(R.string.str_compute_service_charge),
                            mBatchTransferTotalAmount, exchangeRate, percent, serviceCharge + purseunitname, serviceChargeDOS));

                    mMultiUserTransferHolder.currentExchangeRateLayout.setVisibility(View.VISIBLE);
                    mMultiUserTransferHolder.line1.setVisibility(View.VISIBLE);
                }
                exchangeLayout.setVisibility(View.VISIBLE);
                mMultiUserTransferHolder.mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
                if (mAddTransferUserAdapter == null) {
                    mAddTransferUserAdapter = new AddTransferUserAdapter(this, mAddTransferUserModelList);
                }
                mMultiUserTransferHolder.mRecyclerView.setAdapter(mAddTransferUserAdapter);
                mMultiUserTransferHolder.mAddNewAccountTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        isBatchModification = false;
                        addTransferShowDailog();
                    }
                });
                mAddTransferUserAdapter.setOnIsBatchTransferClickListener(this);
                mAddTransferUserAdapter.setOnItemClickListener(this);
                break;
            case Constant.HANDLER_MESSAGE_WHAT_1102:
                if (mFundInfoHolder != null) {
                    mFundInfoHolder.mWalletNameTv.setText(purseName);
                    mFundInfoHolder.mAmountTv.setText(mBalanceformat);
                    mFundInfoHolder.mFreezeLimitTv.setText(mAmountMovement + " " + freeze);
                }
                break;
            case Constant.HANDLER_MESSAGE_WHAT_1103:
                int sum = 0;
                mBatchTransferTotalAmount = "0.0";
                Collections.sort(mAddTransferUserModelList);
                for (int i = 0; i < mAddTransferUserModelList.size(); i++) {
                    AddTransferUserModel model = mAddTransferUserModelList.get(i);
                    String fund = model.getFund();
                    String account = model.getAccount();
                    int status = model.getStatus();
                    if (model.getStatus() == Constant.BATCH_TRANSFER_FAIL) {
                        sum++;
                        isComplete = false;
                        transferAmountTotal = ArithUtils.add(transferAmountTotal, fund, decimalPlaces);
                    }
                }

                String serviceCharge = ArithUtils.serviceCharge(transferAmountTotal, exchangeRate, serviceChargeRate, scale);
                String serviceChargeDOS = ArithUtils.serviceChargeDOS(transferAmountTotal, exchangeRate, serviceChargeRate, mDOSRate, scale);
                serviceChargeTv.setText(serviceChargeDOS);
                serviceChargeComputeTv.setText(String.format(getString(R.string.str_compute_service_charge),
                        mBatchTransferTotalAmount, exchangeRate, percent, serviceCharge + purseunitname, serviceChargeDOS));

                mNeedBatchUserAccount = sum + "";
                if (isComplete) {
                    finish();
                    return false;
                }
                mAddTransferUserAdapter.notifyDataSetChanged();
                dissmissDialog();
                break;
        }
        return false;
    }

    InputFilter[] filters = new InputFilter[]{new InputFilter() {

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            if (source.equals(".") && dest.toString().length() == 0) {
                return "0.";
            }
            if (dest.toString().contains(".")) {
                int index = dest.toString().indexOf(".");
                int length = dest.toString().substring(index).length() - 1;
                if (length == decimalPlaces) {
                    return "";
                }
            }
            return null;
        }
    }};

    public void updataView() {
        if (ArithUtils.compare(mBatchTransferTotalAmount, balance) > 0) {
            ToastUtils.showShort(R.string.str_transfer_amount_limit);
            mMultiUserTransferHolder.mExplain.setVisibility(View.VISIBLE);
            mMultiUserTransferHolder.mExplain.setText(getString(R.string.str_transfer_amount_limit));
            mTransferBtn.setClickable(false);
            mTransferBtn.setBackgroundResource(R.drawable.gray_circular_bead_shape);
        } else {
            mTransferBtn.setClickable(true);
            mMultiUserTransferHolder.mExplain.setText("");
            mMultiUserTransferHolder.mExplain.setVisibility(View.GONE);
            mTransferBtn.setBackgroundResource(R.drawable.yellow_circular_bead_shape);
        }
        if (mAddTransferUserModelList != null) {
            mBatchUserAccount = mAddTransferUserModelList.size() + "";
        } else {
            mBatchUserAccount = "0";
        }
        String serviceCharge = ArithUtils.serviceCharge(mBatchTransferTotalAmount, exchangeRate, serviceChargeRate, scale);
        String serviceChargeDOS = ArithUtils.serviceChargeDOS(mBatchTransferTotalAmount, exchangeRate, serviceChargeRate, mDOSRate, scale);
        serviceChargeTv.setText(serviceChargeDOS);
        serviceChargeComputeTv.setText(String.format(getString(R.string.str_compute_service_charge),
                mBatchTransferTotalAmount, exchangeRate, percent, serviceCharge + purseunitname, serviceChargeDOS));
        mMultiUserTransferHolder.mUserNumberTv.setText(Html.fromHtml(getResources().getString(R.string.total_user_txt, mBatchUserAccount)));
        mMultiUserTransferHolder.mTotalMoneyTv.setText(Html.fromHtml(getResources().getString(R.string.total_money_txt, mBatchTransferTotalAmount)));
    }

    public void initTextChangedListener() {
        if (!isBatch) {
            //InputType.TYPE_NUMBER_FLAG_DECIMAL //小数点型
            //InputType.TYPE_CLASS_NUMBER //整数型
            //设置Input的类型两种都要
            if (mUserTransferHolder != null) {
                mUserTransferHolder.mAmountEnteredEt.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER);
                mUserTransferHolder.mAmountEnteredEt.setHint(String.format(getString(R.string.str_roll_out_hint), mMinTransferNum));
                //设置字符过滤
                mUserTransferHolder.mAmountEnteredEt.setFilters(filters);
                //账号输入框
                mUserTransferHolder.mAccountEt.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                        //输入文本之前的状态
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        //输入文字中的状态，count是一次性输入字符数
                        isCheck = false;
                        mUserTransferHolder.mAccountInfoLayout.setVisibility(View.GONE);
                        if (s.length() > 0) {
                            mUserTransferHolder.mVerifyBtn.setBackgroundResource(R.color.app_color_common_yellow);
                        } else {
                            mUserTransferHolder.mVerifyBtn.setBackgroundResource(R.color.app_color_common_gray);
                        }
                        if ((mUserTransferHolder.mAmountEnteredEt.getText() + "").length() > 0 && s.length() > 0) {
                            mTransferBtn.setBackgroundResource(R.drawable.yellow_circular_bead_shape);
                            mTransferBtn.setClickable(true);
                        } else {
                            mTransferBtn.setBackgroundResource(R.drawable.gray_circular_bead_shape);
                            mTransferBtn.setClickable(false);
                        }
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
//                        String user = s.toString();
//                        if (user == null || "".equals(user) || "null".equals(user) || TextUtils.isEmpty(user)) {
//                            isCheck = false;
//                            mUserTransferHolder.mAccountInfoLayout.setVisibility(View.GONE);
//                        }
                        //输入文字后的状态
                    }
                });
                //转账金额输入框
                mUserTransferHolder.mAmountEnteredEt.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                        //输入文本之前的状态
                    }

                    @SuppressLint("StringFormatInvalid")
                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        //输入文字中的状态，count是一次性输入字符数
                        if (pursetypeid == 3) {
                            if (s.length() > 0) {
//                                手续费 3x50000x0.1%=150元，折合约21.43DOS
                                if (!ObjectUtils.isEmpty(exchangeRate) && !ObjectUtils.equals("null", exchangeRate)) {
                                    try {
                                        if (ArithUtils.compare(s.toString(), "0") >= 0) {
                                            String serviceCharge = ArithUtils.serviceCharge(s.toString(), exchangeRate, serviceChargeRate, scale);
                                            String serviceChargeDOS = ArithUtils.serviceChargeDOS(s.toString(), exchangeRate, serviceChargeRate, mDOSRate, scale);
                                            LogUtils.dTag("BigDecimal==", "serviceCharge = " + serviceCharge + " serviceChargeDOS = " + serviceChargeDOS);
                                            mDetailTv.setText(String.format(getString(R.string.str_compute_service_charge),
                                                    s.toString(), exchangeRate, percent, serviceCharge + purseunitname, serviceChargeDOS));
                                            mDetailTv.setTextColor(ContextCompat.getColor(TransferAccountsActivity.this, R.color.redColor2));
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            } else {
                                mDetailTv.setText(pagetransfer);
                                mDetailTv.setTextColor(ContextCompat.getColor(TransferAccountsActivity.this, R.color.grayColor));
                            }
                        } else {
                            if (s.length() > 0) {
                                mUserTransferHolder.mDelIv.setVisibility(View.VISIBLE);
                            } else {
                                mUserTransferHolder.mDelIv.setVisibility(View.GONE);
                            }
                        }
                        if ((mUserTransferHolder.mAccountEt.getText() + "").length() > 0 && s.length() > 0) {
                            mTransferBtn.setBackgroundResource(R.drawable.yellow_circular_bead_shape);
                            mTransferBtn.setClickable(true);
                        } else {
                            mTransferBtn.setBackgroundResource(R.drawable.gray_circular_bead_shape);
                            mTransferBtn.setClickable(false);
                        }
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        //输入文字后的状态
                        String numberStr = s.toString() + "";
                        if (numberStr == null || "".equals(numberStr) || "null".equals(numberStr)) {
                            mTransferBtn.setBackgroundResource(R.drawable.gray_circular_bead_shape);
                            mTransferBtn.setClickable(false);
                        } else {
                            if (ArithUtils.compare(numberStr, mMinTransferNum) >= 0) {
                                mTransferBtn.setBackgroundResource(R.drawable.yellow_circular_bead_shape);
                                mTransferBtn.setClickable(true);
                            } else {
                                mTransferBtn.setBackgroundResource(R.drawable.gray_circular_bead_shape);
                                mTransferBtn.setClickable(false);
                            }
                            if (ArithUtils.compare(numberStr, balance) > 0) {
                                ToastUtils.showShort(R.string.str_transfer_amount_limit);
                            }
                        }
                    }
                });
            }
        } else {
            if (mMultiUserTransferHolder != null) {
//                mMultiUserTransferHolder.
            }
        }

    }

    private void getBatchTransferData() {
        if (mAddTransferUserModelList != null) {
            mBatchUserAccount = mAddTransferUserModelList.size() + "";
            if (mAddTransferUserModelList.size() > 0) {
                for (int i = 0; i < mAddTransferUserModelList.size(); i++) {
                    AddTransferUserModel model = mAddTransferUserModelList.get(i);
                    String account = model.getAccount();
                    String fund = model.getFund();
                    if (fund == null || "".equals(fund)) {
                    } else {
                        mBatchTransferTotalAmount = ArithUtils.add(mBatchTransferTotalAmount, fund, decimalPlaces);
                    }

                }
            }
        } else {
            mBatchUserAccount = "0";
        }
    }

    private void batchTransfer(final String password) {
        showLoading();
        mThread = new Thread(new Runnable() {
            @Override
            public void run() {
                if (mAddTransferUserModelList != null) {
                    batchTransferNumber = mAddTransferUserModelList.size();
                    if (batchTransferNumber > 0) {
                        for (int i = 0; i < batchTransferNumber; i++) {
                            pointer = i;
                            model = mAddTransferUserModelList.get(i);
                            String account = model.getAccount();
                            String fund = model.getFund();
                            int status = model.getStatus();
                            if (status != Constant.BATCH_TRANSFER_SUCCEED) {
                                purseTransfer(account, fund, password);
                                try {
                                    mThread.join();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {
                                if (i == batchTransferNumber - 1) {
                                    Message message = Message.obtain();
                                    message.what = Constant.HANDLER_MESSAGE_WHAT_1103;
                                    mHandler.sendMessage(message);
                                }
                            }

                        }
                    }
                }
            }
        });
        mThread.start();
    }

    @Override
    public void onCheckAccountClick(View view) {
        if (mUserTransferHolder != null) {
            mUserAccount = mUserTransferHolder.mAccountEt.getText() + "";
        }
        if ("".equals(mUserAccount) || mUserAccount == null || "null".equals(mUserAccount)) {
            ToastUtils.showShort(R.string.toast_account_can_not_empty);
            return;
        }
        clickCheckAccount();
    }

    @Override
    public void onDeleteAmountClick(View view) {
        if (mUserTransferHolder != null) {
            mUserTransferHolder.mAmountEnteredEt.setText("");
        }
    }

    @Override
    public void onFullAmountClick(View view) {
        if (mUserTransferHolder != null) {
            mUserTransferHolder.mAmountEnteredEt.setText(balance);
        }
    }

    private void reconfirmDialog() {
        boolean isPayPwd = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getBoolean(Constant.IS_PAY_PWD, true);
        if (isPayPwd) {
            //没有支付密码
            new QMUIDialog.MessageDialogBuilder(this)
                    .setTitle(getResources().getString(R.string.str_not_setting_pay_pwd))
                    .setMessage(getResources().getString(R.string.str_you_not_setting_pay_pwd_not_user))
                    .addAction(getResources().getString(R.string.str_later), new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                        }
                    })
                    .addAction(getResources().getString(R.string.str_right_now_setting), new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                            Intent settingPayPwdIntent = new Intent(TransferAccountsActivity.this, ForgetPasswordActivity.class);
                            settingPayPwdIntent.putExtra("pwd", "pay");
                            startActivity(settingPayPwdIntent);

                        }
                    }).show();
        } else {
            Spanned message;
            if (isBatch) {//批量转账
                if (isComplete) {
                    mNeedBatchUserAccount = mBatchUserAccount;
                    transferAmountTotal = mBatchTransferTotalAmount;
                }
                message = Html.fromHtml(getResources().getString(R.string.str_reconfirm_batch_msg_dialog, mNeedBatchUserAccount,
                        transferAmountTotal + purseunitname));

            } else {
                if (mUserTransferHolder != null) {
                    mUserAccount = mUserTransferHolder.mAccountEt.getText() + "";
                    mTransferAmount = mUserTransferHolder.mAmountEnteredEt.getText() + "";
                } else {
                    mUserAccount = "null";
                    mTransferAmount = "0";
                }
                message = Html.fromHtml(getResources().getString(R.string.str_reconfirm_msg_dialog, mTransferAmount + purseunitname,
                        mUserAccount + getResources().getString(R.string.str_account_number)));
                transferAmountTotal = mTransferAmount;
            }

            DialogHelper.showMessageDialog(this, getResources().getString(R.string.str_reconfirm_title_dialog),
                    message,
                    getResources().getString(R.string.str_reconfirm_negative_dialog),
                    getResources().getString(R.string.str_reconfirm_positive_dialog), new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                        }
                    }, new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                            inputPassword();
                        }
                    });
        }
    }

    private void inputPassword() {
        if (ArithUtils.compare(transferAmountTotal, balance) <= 0) {
            if (simplePayPopWindow == null) {
                simplePayPopWindow = new SimplePayPopWindow(TransferAccountsActivity.this);
            }
            simplePayPopWindow.setTvPayValue(transferAmountTotal + purseunitname);//实际支付金额
            simplePayPopWindow.setPayTypeImageUrl(pursepic);
            simplePayPopWindow.setTvPayType(purseunitname);
            simplePayPopWindow.setTvBalance(mBalanceformat);
            simplePayPopWindow.showAtLocation(mTransferBtn, Gravity.BOTTOM, 0, 0);
            simplePayPopWindow.setOnPayListener(new BasePayPop.PayEnterPassWordListener() {
                @Override
                public void onCancel() {
                    simplePayPopWindow.dismiss();
                }

                @Override
                public void onInputFinished(String passWord) {
                    passWord = EncodeUtils.base64Encode2String(passWord.getBytes());
                    //支付密码输入完成
                    if (isBatch) {
                        batchTransfer(passWord);
                    } else {
                        purseTransfer(mUserAccount, mTransferAmount, passWord);
                    }
//                  Toast.makeText(MainActivity.this,"密码："+passWord,Toast.LENGTH_LONG).show();
                }
            });

//            Intent pwdIntent = new Intent(TransferAccountsActivity.this, PaymentPasswordActivity.class);
//            pwdIntent.putExtra("amount", transferAmountTotal + unit);
//            pwdIntent.putExtra("subject", purseName + getResources().getString(R.string.transfer_accounts_txt));
//            //密码输入界面需要显示的参数
//            pwdIntent.putExtra("pursename", purseName);
//            pwdIntent.putExtra("icon", pursepic);
//            pwdIntent.putExtra("balance", balance);
//            startActivityForResult(pwdIntent, INTENT_REQUEST_TRANSFER_CODE);
        } else {
            ToastUtils.showShort(getResources().getString(R.string.str_insufficient_balance));
        }
    }

    @OnClick({R.id.massTransferBtn, R.id.transferBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.massTransferBtn:
                Message message = new Message();
                message.what = Constant.HANDLER_MESSAGE_WHAT_1101;
                mHandler.sendMessage(message);
                break;
            case R.id.transferBtn:
                if (isBatch) {//批量转账
                    reconfirmDialog();
                    return;
                } else {
                    if (!isCheck) {
                        ToastUtils.showShort(R.string.str_please_check_account);
                        return;
                    }
                    if (mUserTransferHolder != null) {
                        mUserAccount = mUserTransferHolder.mAccountEt.getText() + "";
                        mTransferAmount = mUserTransferHolder.mAmountEnteredEt.getText() + "";
                    }
                }
                if ("".equals(mUserAccount) || mUserAccount == null || "null".equals(mUserAccount)) {
                    ToastUtils.showShort(R.string.toast_account_can_not_empty);
                    return;
                }
                if ("".equals(mTransferAmount) || mTransferAmount == null || "0".equals(mTransferAmount)) {
                    ToastUtils.showShort(R.string.toast_amount_can_not_empty);
                    return;
                }
                if (ObjectUtils.isEmpty(exchangeRate) || ObjectUtils.equals("null", exchangeRate)) {
                    ToastUtils.showShort(R.string.toast_rate_get_fail);
                    return;
                }
                reconfirmDialog();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == INTENT_REQUEST_TRANSFER_CODE && resultCode == RESULT_OK) {
            String pwd = data.getStringExtra("inputFinish");
            //支付密码输入完成
            if (isBatch) {
                batchTransfer(pwd);
            } else {
                purseTransfer(mUserAccount, mTransferAmount, pwd);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dissmissDialog();
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (isBatch) {
                mAddTransferUserAdapter.removeAllData();
                initTransferUserView();
                return true;
            } else {
                finish();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onIsBatchTransferClick(AddTransferUserModel mAddTransferUserModel, int position) {
//        if (isClickable) {
//            mTransferBtn.setBackgroundResource(R.drawable.yellow_circular_bead_shape);
//        } else {
//            mTransferBtn.setBackgroundResource(R.drawable.gray_circular_bead_shape);
//        }
//        if (mMultiUserTransferHolder != null) {
//            if (status.length() <= 0) {
//                mMultiUserTransferHolder.mExplain.setVisibility(View.GONE);
//            }
//            mMultiUserTransferHolder.mExplain.setText(status);
//        }
//        mTransferBtn.setClickable(isClickable);

        mAddTransferUserModelList.remove(mAddTransferUserModel);
        mAddTransferUserAdapter.removeData(position);
        mBatchTransferTotalAmount = ArithUtils.subtract(mBatchTransferTotalAmount, mAddTransferUserModel.getFund(), decimalPlaces);
        updataView();
    }

    private EditText mAccountEdit;
    private EditText mAmountEdit;
    private TextView explainTv;
    private String explain = "";
    private boolean isCanAdd = false;
    private String str1 = "";
    private String str2 = "";

    @SuppressLint("StringFormatInvalid")
    public QMUIDialog initAddTransferDialog() {
        str1 = getResources().getString(R.string.str_transfer_in_account_hint);
        str2 = String.format(getString(R.string.str_transfer_in_money_hint), mMinTransferNum);
        QMAutoTestDialogBuilder autoTestDialogBuilder = (QMAutoTestDialogBuilder) new QMAutoTestDialogBuilder(TransferAccountsActivity.this)
                .setTitle(R.string.str_add_transfer_title)
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        explain = "";
                        isCanAdd = false;
                        str1 = "";
                        str2 = "";
                        mAccountEdit.setText("");
                        mAmountEdit.setText("");
                        dialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        isCanAdd = checkData();
                        if (isCanAdd) {
                            String account = mAccountEdit.getText() + "";
                            String amount = mAmountEdit.getText() + "";
                            if (isBatchModification) {
                                mBatchTransferTotalAmount = ArithUtils.subtract(mBatchTransferTotalAmount, mModificationAddTransferModel.getFund(), decimalPlaces);
                                mModificationAddTransferModel.setAccount(account);
                                mModificationAddTransferModel.setFund(amount);
                                mAddTransferUserAdapter.notifyItemChanged(mModificationAddTransferModel.getId());
                            } else {
                                explain = "";
                                isCanAdd = false;
                                str1 = "";
                                str2 = "";
                                AddTransferUserModel model = new AddTransferUserModel();
                                model.setAccount(account);
                                model.setFund(amount);
                                mAddTransferUserModelList.add(model);
                                mAddTransferUserAdapter.notifyDataSetChanged();
                                explainTv.setText(explain);
                                explainTv.setVisibility(View.GONE);
                            }
                            mBatchTransferTotalAmount = ArithUtils.add(mBatchTransferTotalAmount, amount, decimalPlaces);
                            updataView();
                        } else {
                            explainTv.setText(explain);
                            explainTv.setVisibility(View.VISIBLE);
                            return;
                        }
                        mAccountEdit.setText("");
                        mAmountEdit.setText("");
                        dialog.dismiss();
                    }
                });
        autoTestDialogBuilder.setCancelable(false);
        QMUIDialog dialog = autoTestDialogBuilder.create();
        mAccountEdit = autoTestDialogBuilder.getAccountEditText();
        mAmountEdit = autoTestDialogBuilder.getAmountEditText();
        explainTv = autoTestDialogBuilder.getExplainTextView();
        mAmountEdit.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER);
        //设置字符过滤
        mAmountEdit.setFilters(filters);
        mAmountEdit.setHint(String.format(getString(R.string.str_roll_out_hint), mMinTransferNum));
        mAccountEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                isCanAdd = checkData();
                if (isCanAdd) {
                    explainTv.setVisibility(View.GONE);
                } else {
                    explainTv.setText(explain);
                    explainTv.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                isCanAdd = checkData();
                if (isCanAdd) {
                    explainTv.setVisibility(View.GONE);
                } else {
                    explainTv.setText(explain);
                    explainTv.setVisibility(View.VISIBLE);
                }
            }
        });
        mAmountEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                isCanAdd = checkData();
                if (isCanAdd) {
                    explainTv.setVisibility(View.GONE);
                } else {
                    explainTv.setText(explain);
                    explainTv.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                isCanAdd = checkData();
                if (isCanAdd) {
                    explainTv.setVisibility(View.GONE);
                } else {
                    explainTv.setText(explain);
                    explainTv.setVisibility(View.VISIBLE);
                }
            }
        });
        isCanAdd = checkData();
        if (isCanAdd) {
            explainTv.setVisibility(View.GONE);
        } else {
            explainTv.setText(explain);
            explainTv.setVisibility(View.VISIBLE);
        }
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (KeybordUtils.isSoftInputShow(TransferAccountsActivity.this)) {
                    KeybordUtils.closeKeybord(mAccountEdit, TransferAccountsActivity.this);
                }
            }
        });
        return dialog;
    }

    public boolean checkData() {
        String account = mAccountEdit.getText() + "";
        String fund = mAmountEdit.getText() + "";

        if (account == null || "".equals(account) || "null".equals(account)
                || fund == null || "".equals(fund) || "null".equals(fund)) {
            explain = "";
            str1 = "";
            str2 = "";
            if (fund == null || "".equals(fund) || "null".equals(fund)) {
                str2 = String.format(getString(R.string.str_transfer_in_money_hint), mMinTransferNum);
            }
            if (account == null || "".equals(account) || "null".equals(account)) {
                str1 = getResources().getString(R.string.str_transfer_in_account_hint);
            }
            explain = !"".equals(str1) && !"".equals(str2) ? "1、" + str1 + ";\n2、" + str2 + ";" : str1 + str2;
            return false;
        } else {
            explain = "";
            str1 = "";
            str2 = "";
            if (ArithUtils.compare(fund, mMinTransferNum) < 0) {
                explain = String.format(getString(R.string.str_transfer_in_money_hint), mMinTransferNum);
                return false;
            }
            if (ArithUtils.compare(fund, balance) > 0) {
                explain = getResources().getString(R.string.str_transfer_amount_limit);
                return false;
            }
        }
        return true;
    }

    private void addTransferDismissDailog() {
        if (mQMUIDialog != null) {
            if (mQMUIDialog.isShowing()) {
                mQMUIDialog.dismiss();
            }
        }
    }


    private void addTransferShowDailog() {
        if (mQMUIDialog != null) {
            if (!mQMUIDialog.isShowing()) {
                mAccountEdit.requestFocus();
                mQMUIDialog.show();
                KeybordUtils.openKeybord(mAccountEdit, TransferAccountsActivity.this);
//                QMUIKeyboardHelper.showKeyboard(mAccountEdit, true);
            }
        }
    }

    @Override
    public void onItemClick(View view, int postion) {
        mModificationAddTransferModel = mAddTransferUserModelList.get(postion);
        isBatchModification = true;
        addTransferShowDailog();
//        LogUtils.dTag("onItemClick==", "onItemClick== Account = " + model.getAccount() + " Fund = " + model.getFund());
    }

    public class QMAutoTestDialogBuilder extends QMUIDialog.AutoResizeDialogBuilder {
        @BindView(R.id.accountDiaTv)
        public TextView accountDiaTv;
        @BindView(R.id.accountDiaEt)
        public EditText accountDiaEt;
        @BindView(R.id.line2)
        public View line2;
        @BindView(R.id.amountDaiTv)
        public TextView amountDaiTv;
        @BindView(R.id.amountDaiEt)
        public EditText amountDaiEt;
        @BindView(R.id.delDaiIv)
        public ImageView delDaiIv;
        @BindView(R.id.explainDai)
        public TextView explainDai;
        private Context mContext;

        public QMAutoTestDialogBuilder(Context context) {
            super(context);
            mContext = context;
        }

        public EditText getAccountEditText() {
            return accountDiaEt;
        }

        public EditText getAmountEditText() {
            return amountDaiEt;
        }

        public TextView getExplainTextView() {
            return explainDai;
        }

        @Override
        public View onBuildContent(QMUIDialog dialog, ScrollView parent) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_add_transfer_info, null);
            ButterKnife.bind(this, view);
            return view;
        }
    }

    private void purseTransfer(String tonodecode, String amount, String paypwd) {
        if (!isBatch) {
            showLoading();
        }
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getPurseTansferUrl(), NETWORK_REQUEST_PURSE_TRANSFER,
                Params.getPurseTransferParams(purseid, tonodecode, amount, paypwd, pursetypeid, exchangeRate));
    }

    private void clickCheckAccount() {
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getUserBaseInfoUrl(), NETWORK_REQUEST_USER_INFO,
                Params.getUserInfoParams(mUserAccount, purseid));
    }

    private void getSubPurses() {
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getSubPursesUrl(), NETWORK_REQUEST_SUB_PURSES,
                Params.getSubPursesParams(purseid));
    }

    private void getExchangeRateByPurse() {
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getExchangeRateByPurseUrl(), NETWORK_REQUEST_EXCHANGERATEBY_PURSES,
                Params.getExchangeRateByPurseParams(mId + ""));
    }

    private void getMinTransferNum() {
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getMinTransferNumUrl(), NETWORK_REQUEST_MINTRANSFER_NUM,
                Params.getMinTransferNumParams(mId + ""));
    }
}
